//cc bdb.c -I/usr/local/include -L/usr/local/lib/db47 -ldb-4.7

#include <db47/db.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

DB *dbp;           /* DB structure handle */
u_int32_t flags;   /* database open flags */
int ret;           /* function return value */

int
main(void)
{
            uint32_t env_flags;
    DB_ENV *envp;
    const char *db_home_dir = "./";
        envp = NULL;

    /* Open the environment */
    ret = db_env_create(&envp, 0);
    
    env_flags = DB_CREATE |    /* Create the environment if it does 
                                * not already exist. */
                DB_INIT_TXN  | /* Initialize transactions */
                DB_INIT_LOCK | /* Initialize locking. */
                DB_INIT_LOG  | /* Initialize logging */
                DB_INIT_MPOOL; /* Initialize the in-memory cache. */
    ret = envp->open(envp, db_home_dir, env_flags, 0);
                char buf[8];
        ret = db_create(&dbp, envp, 0);
        if (ret != 0) {
                /* error */
        }
        dbp->set_re_len(dbp, 500);
        dbp->set_re_pad(dbp, 0);
        dbp->set_q_extentsize(dbp, 128);
        dbp->set_pagesize(dbp, 16*1024);
//envp->set_cachesize(envp, 0, 128*1024*1024, 4);
        flags = DB_CREATE;

        ret = dbp->open(dbp, NULL, "queue.db", NULL, DB_QUEUE, flags, 0);
        int k;
        DBT key, data;
        DBT gkey, gdata;
        int i;
        
        memset(&key, 0, sizeof(DBT));
        memset(&data, 0, sizeof(DBT));
        memset(&gkey, 0, sizeof(DBT));
        memset(&gdata, 0, sizeof(DBT));
        
        key.data = "x";
        key.size = 2;
        gkey.data = "y";
        gkey.size = 2;
        for (i = 0; i < 10000; i++) {
                        sprintf(buf, "%07d", i);
                data.data = buf;
                data.size = 8;
                dbp->put(dbp, NULL, &key, &data, DB_APPEND);
         //       dbp->sync(dbp, 0);
        }
        for (i = 0; i < 10000; i++) {
                ret = dbp->get(dbp, 0, &gkey, &gdata, DB_CONSUME);
                if (ret == DB_NOTFOUND)
                        break;
//        printf("%s\n", gdata.data);
        }
        dbp->close(dbp, 0);
        envp->close(envp, 0);
        return 0;
}
